package com.jing21.learn.authorizationservice.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * Created by lenovo07 on 2016/12/17.
 */
@Component
public class CustomUserDetailService implements UserDetailsService {


	private static final String ADMINISTRATOR = "zhengjing";

	private static final String ADMINISTRATOR_PASSWORD = "123456";
	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	PasswordEncoder passwordEncoder;
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		if(ADMINISTRATOR.equals(username)){

			return new User(ADMINISTRATOR, passwordEncoder.encode(ADMINISTRATOR_PASSWORD)
			, AuthorityUtils.createAuthorityList("ADMIN"));
		}

		Map<String, Object> obj = restTemplate
				.getForObject("http://BASIC-SERVICE/user/findByUnque?loginname=" + username, Map.class);

		if (obj == null)
			return null;

		return new User(username, obj.get("password").toString(), AuthorityUtils.NO_AUTHORITIES);
	}
}
